<?php

namespace app\model;

use think\Model;

class Admin extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'admin';
    // 设置当前模型主键
    protected $pk = 'id';

    /**
     * 根据id获取数据
     * 
     * @dateTime 2022/09/03
     * @author zhixiang0215@126.com
     * @param int id
     * @param string fields
     * @return array
    */
    public function getInfoById(int $id, string $fields = 'id')
    {
        $data = $this::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 根据条件获取数据
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @return array
    */
    public function getInfoByWhere(array $where, string $fields = 'id')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    /**
     * 新增/更新
     * 
     * @dateTime 2022/08/24
     * @param array $params
     * @return fixed
     */
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = $this::create($params);
            return $data->id;
        }
        $this::update($params);
        return $params['id'];
    }

    /**
     * 根据条件获取数据
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param array where
     * @param string fields
     * @return array
    */
    public function getDataByWhere(array $where = [], string $fields = 'id', $order = 'id asc')
    {
        $data = $this::where($where)->field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    // 获取分页数据
    public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, string $fields = 'id, name', $order = 'id asc')
    {
        $total = $this::where($where)->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $offset = ($page - 1) * $limit;
        $totalPage = ceil($total / $limit);

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    /**
     * 删除管理员
     * 
     * @author zhixiang0215@126.com
     * @param int $id
     * @return fixed|bool
     */
    public function deleteAdminManager($id)
    {
        $model = $this::find($id);
        return $model->save([
            'is_delete' => 2,
            'deleted_at' => time()
        ]);
    }

    /**
     * 获取总数
     * 
     * @author zhixiang0215@126.com
     * @return int
     */
    public function getCounts()
    {
        $count = $this::where(['is_delete' => 1])->count();
        return $count;
    }
}